<template>
  <div class="gpu-page">
    <div class="tab-bg">
      <img
        class="tab-bg-img"
        v-if="activeTab === 'working'"
        src="@/assets/images/tab1-bg1.png"
        alt=""
      />
      <img
        class="tab-bg-img"
        v-if="activeTab === 'expired'"
        src="@/assets/images/tab1-bg2.png"
        alt=""
      />
    </div>

    <div class="tabs">
      <div
        class="tab-item"
        :class="{ active: activeTab === 'working' }"
        @click="switchTab('working')"
      >
        {{ t("svipopen_working") }}
        <div class="tab-indicator" v-if="activeTab === 'working'"></div>
      </div>
      <div
        class="tab-item"
        :class="{ active: activeTab === 'expired' }"
        @click="switchTab('expired')"
      >
        {{ t("user-gpu_expired") }}
        <div class="tab-indicator" v-if="activeTab === 'expired'"></div>
      </div>
    </div>

    <!-- 工作中的GPU选项卡 -->
    <div v-if="activeTab === 'working'" class="gpu-content">
      <div v-if="workingOrders.length === 0 && !loading" class="empty-state">
        <NoData />
      </div>
      <van-list
        v-else
        v-model:loading="loadingMore"
        :finished="finishedWorking"
        :finished-text="t('profitrecord_noMoreData')"
        @load="loadMoreData('0')"
      >
        <div class="gpu-item" v-for="order in workingOrders" :key="order.id">
          <div class="gpu-header">
            <div class="gpu-img">
              <img :src="order.logo" :alt="order.name" />
            </div>
            <div class="gpu-basic-info">
              <div class="gpu-title">{{ order.name }}</div>
              <div class="gpu-validity">
                <span class="dot"></span>
                {{ t("profitrecord_validPeriod") }} {{ order.endTime }}
              </div>
              <div class="gpu-profit">{{ t("user-gpu_keuntungan24jam") }}</div>
            </div>
          </div>

          <div class="countdown-operation-row">
            <div class="countdown-block">
              <div class="timer-label">{{ t("user-gpu_perolehanJarak") }}</div>
              <div class="timer">
                {{ formatNextProfit(order.nextProfitTime) }}
              </div>
            </div>

            <div class="operation-btns">
              <div class="view-btn" @click="navigateToGpuDetail(order)">
                <img src="@/assets/images/d-bg1.png" alt="View" />
              </div>
              <div
                class="operate-btn loading"
                :class="{ 'can-receive': order.receivestate == '1' }"
                @click="operateGpu(order)"
              >
                <div
                  v-if="order.receivestate != '1'"
                  class="loading-circle"
                ></div>
                <span>{{
                  order.receivestate == "1"
                    ? t("user-gpu_terima")
                    : t("user-gpu_beroperasi")
                }}</span>
              </div>
            </div>
          </div>

          <div class="gpu-details">
            <div class="detail-row">
              <div class="detail-label">{{ t("gpuinfo_price") }}</div>
              <div class="detail-value">COP{{ formatNumber(order.price) }}</div>
            </div>
            <div class="detail-row">
              <div class="detail-label">{{ t("products_income") }}</div>
              <div class="detail-value">
                COP{{ formatNumber(calculateDailyProfit(order)) }}
                {{ t("products_perDay") }}
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-label">{{ t("user-gpu_waktuBerjalan") }}</div>
              <div class="detail-value">
                {{ order.onCycle }}{{ t("products_day") }}
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </div>

    <!-- 过期的GPU选项卡 -->
    <div v-if="activeTab === 'expired'" class="gpu-content">
      <div v-if="expiredOrders.length === 0 && !loading" class="empty-state">
        <NoData />
      </div>
      <van-list
        v-else
        v-model:loading="loadingMore"
        :finished="finishedExpired"
        :finished-text="t('profitrecord_noMoreData')"
        @load="loadMoreData('1')"
      >
        <div class="gpu-item" v-for="order in expiredOrders" :key="order.id">
          <div class="gpu-header">
            <div class="gpu-img">
              <img :src="order.logo" :alt="order.name" />
            </div>
            <div class="gpu-basic-info">
              <div class="gpu-title">{{ order.name }}</div>
              <div class="gpu-validity">
                <span class="dot"></span>
                {{ t("profitrecord_validPeriod") }} {{ order.endTime }}
              </div>
              <div class="gpu-profit">{{ t("user-gpu_keuntungan24jam") }}</div>
            </div>
          </div>

          <div class="countdown-operation-row">
            <div class="countdown-block">
              <div class="timer-label">{{ t("user-gpu_perolehanJarak") }}</div>
              <div class="timer">00:00:00</div>
            </div>

            <div class="operation-btns">
              <div class="view-btn" @click="navigateToGpuDetail(order)">
                <img src="@/assets/images/d-bg1.png" alt="View" />
              </div>
              <div class="operate-btn expired">
                <span>{{ t("user-gpu_expired") }}</span>
              </div>
            </div>
          </div>

          <div class="gpu-details">
            <div class="detail-row">
              <div class="detail-label">{{ t("gpuinfo_price") }}</div>
              <div class="detail-value">COP{{ formatNumber(order.price) }}</div>
            </div>
            <div class="detail-row">
              <div class="detail-label">{{ t("products_income") }}</div>
              <div class="detail-value">
                COP{{ formatNumber(calculateDailyProfit(order)) }} {{ t("products_perDay") }}
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-label">{{ t("user-gpu_waktuBerjalan") }}</div>
              <div class="detail-value">{{ order.onCycle }} {{ t("products_day") }}</div>
            </div>
          </div>
        </div>
      </van-list>
    </div>

    <!-- 加载状态 -->
    <div class="loading-container" v-if="loading">
      <van-loading type="spinner" color="#f6eade" size="24px" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { lockMallOrder, receiveLockOrderIncome } from "@/api/products";
import NoData from "@/components/NoData.vue";
import { formatNumber } from "@/utils/public";
import { showToast } from "vant";
import { onMounted, onUnmounted, ref } from "vue";
import { useRouter, useRoute } from "vue-router";

const router = useRouter();
const route = useRoute();
const activeTab = ref("working");
const loading = ref(false);
const loadingMore = ref(false);
const workingOrders = ref<any[]>([]);
const expiredOrders = ref<any[]>([]);
const currentPage = ref(1);
const pageSize = 10;
const timerInterval = ref<NodeJS.Timeout | null>(null);
const finishedWorking = ref(false);
const finishedExpired = ref(false);
const { t } = useI18n();
const totalPages = ref({
  working: 1,
  expired: 1,
});
const isFirstLoad = ref(true);

// 切换标签页
function switchTab(tab: string) {
  activeTab.value = tab;

  if (tab === "working") {
    if (workingOrders.value.length === 0) {
      currentPage.value = 1;
      finishedWorking.value = false;
      isFirstLoad.value = true;
      getGpuData("0");
    }
  } else if (tab === "expired") {
    if (expiredOrders.value.length === 0) {
      currentPage.value = 1;
      finishedExpired.value = false;
      isFirstLoad.value = true;
      getGpuData("1");
    }
  }
}

// 加载更多数据
async function loadMoreData(type: string) {
  // 首次加载时不执行loadMore
  if (isFirstLoad.value) {
    isFirstLoad.value = false;
    loadingMore.value = false;
    return;
  }
  if (
    (type === "0" && finishedWorking.value) ||
    (type === "1" && finishedExpired.value)
  ) {
    loadingMore.value = false;
    return;
  }
  currentPage.value += 1;
  await getMoreGpuData(type);
}

// 获取更多GPU数据
async function getMoreGpuData(type: string) {
  try {
    loadingMore.value = true;
    const res = await lockMallOrder({
      type: type,
      page: currentPage.value.toString(),
      limit: pageSize.toString(),
    });

    if (res.code === 200) {
      const newData = res.data || [];

      if (type === "0") {
        if (newData.length > 0) {
          workingOrders.value = [...workingOrders.value, ...newData];
          // 更新工作中GPU的倒计时
          updateTimers();
        } else {
          finishedWorking.value = true;
        }
      } else {
        if (newData.length > 0) {
          expiredOrders.value = [...expiredOrders.value, ...newData];
        } else {
          finishedExpired.value = true;
        }
      }

      // 如果返回的数据少于分页大小，说明没有更多数据了
      if (newData.length < pageSize) {
        if (type === "0") {
          finishedWorking.value = true;
        } else {
          finishedExpired.value = true;
        }
      }
    } else {
      showToast(res.msg);
      if (type === "0") {
        finishedWorking.value = true;
      } else {
        finishedExpired.value = true;
      }
    }
  } catch (error) {
    console.error("err", error);
    showToast(t('products_networkError'));
    if (type === "0") {
      finishedWorking.value = true;
    } else {
      finishedExpired.value = true;
    }
  } finally {
    loadingMore.value = false;
  }
}

// 格式化下次领取收益时间 (秒数转换为 hh:mm:ss 格式)
function formatNextProfit(seconds: string) {
  const totalSeconds = parseInt(seconds);
  if (isNaN(totalSeconds) || totalSeconds <= 0) return "00:00:00";

  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const secs = totalSeconds % 60;

  return `${hours.toString().padStart(2, "0")}:${minutes.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`;
}

// 计算每日收益范围
function calculateDailyProfit(order: any) {
  if (!order) return "0";

  const price = parseFloat(order.price);
  const dayIncomeHigh = parseFloat(order.dayIncomeHigh);

  if (isNaN(price) || isNaN(dayIncomeHigh)) return "0";

  const highProfit = Math.round(price * dayIncomeHigh);

  return `${highProfit}`;
}

// 跳转到GPU详情/收益记录页面
const navigateToGpuDetail = (order: any) => {
  router.push({
    path: "/console/profitrecord",
    query: {
      id: order.id,
      income: order.income,
      creatTime: order.creatTime,
      endTime: order.endTime,
    },
  });
};

// 获取GPU数据
async function getGpuData(type: string) {
  try {
    loading.value = true;
    const res = await lockMallOrder({
      type: type,
      page: currentPage.value.toString(),
      limit: pageSize.toString(),
    });

    if (res.code === 200) {
      if (type === "0") {
        workingOrders.value = res.data || [];
        // 判断是否有更多数据
        finishedWorking.value = (res.data || []).length < pageSize;
        // 更新工作中GPU的倒计时
        updateTimers();
      } else {
        expiredOrders.value = res.data || [];
        // 判断是否有更多数据
        finishedExpired.value = (res.data || []).length < pageSize;
      }
    } else {
      showToast(res.msg);
    }
  } catch (error) {
    console.error("gpu", error);
    showToast(t('products_networkError'));
  } finally {
    loading.value = false;
  }
}

// 更新所有工作中GPU的倒计时
function updateTimers() {
  if (timerInterval.value) {
    clearInterval(timerInterval.value);
  }

  timerInterval.value = setInterval(() => {
    if (workingOrders.value.length === 0) return;

    workingOrders.value = workingOrders.value.map((order) => {
      let nextProfit = parseInt(order.nextProfitTime);
      if (!isNaN(nextProfit) && nextProfit > 0) {
        nextProfit--;
        return { ...order, nextProfitTime: nextProfit.toString() };
      }
      return order;
    });
  }, 1000);
}

// 操作GPU (领取收益或其他操作)
async function operateGpu(order: any) {
  if (order.receivestate == "1") {
    // 可以领取收益
    try {
      loading.value = true;
      const res = await receiveLockOrderIncome({ id: order.id });
      if (res.code == 200) {
        showToast(res.msg);
        // 刷新当前tab数据
        getGpuData(activeTab.value === "working" ? "0" : "1");
      } else {
        showToast(res.msg);
      }
    } catch (error) {
      showToast(t('products_networkError'));
    } finally {
      loading.value = false;
    }
  } else {
    showToast(t('user-gpu_perangkatBelumMenghasilkan'));
  }
}

// 组件挂载时获取数据
onMounted(() => {
  isFirstLoad.value = true;
  getGpuData("0");
});

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value);
  }
});
</script>

<style scoped>
.gpu-page {
  overflow: hidden;
  min-height: 100vh;
  background: #0c0906;
  color: #f6eade;
  position: relative;
  background: url("@/assets/images/login/topBg.png") no-repeat top;
  background-size: 100% auto;
}

.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.tab-bg {
  position: absolute;
  top: 17px;
  left: 0;
  width: 100%;
  z-index: 0;
  display: flex;
  justify-content: center;
}

.tab-bg-img {
  width: 100%;
  height: auto;
  aspect-ratio: 750 / 770; /* 维持原始宽高比 */
  object-fit: cover;
}

.tabs {
  position: relative;
  display: flex;
  background: transparent;
  border-bottom: none;
  overflow: hidden;
  height: 54px;
  margin: 17px 15px 0 15px;
  z-index: 1;
}

.tab-item {
  color: #f6eade;
  position: relative;
  z-index: 2;
  height: 45px;
  flex: 1;
  text-align: center;
  line-height: 45px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  font-size: 17px;
}

.tab-item.active {
  color: #f6eade;
  font-size: 18px;
  font-weight: 700;
}

.tab-indicator {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 20px;
  height: 2px;
  background: #f6eade;
}

.gpu-content {
  padding: 17px;
}

.empty-state {
  margin-top: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.gpu-item {
  margin-top: 17px;
  border-radius: 9px;
  margin-bottom: 11px;
  overflow: hidden;
  background: linear-gradient(
    180deg,
    rgba(254, 242, 230, 0) 4%,
    rgba(254, 237, 221, 0.1) 62%
  );
}

.gpu-header {
  padding: 9px 15px 9px;
  display: flex;
  background: rgba(254, 242, 230, 0.1);
}

.gpu-img {
  width: 131px;
  height: 80px;
  margin-right: 22px;
  flex-shrink: 0 
}

.gpu-img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.gpu-basic-info {
}

.gpu-title {
  max-width: 170px;
  font-size: 17px;
  font-weight: 700;
  color: #f6eade;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  margin-bottom: 6px;
}

.gpu-validity {
  display: flex;
  align-items: center;
  font-size: 13px;
  color: rgba(246, 234, 222, 0.6);
  margin-bottom: 8px;
}

.dot {
  width: 13px;
  height: 13px;
  margin-right: 3px;
  background-image: url("@/assets/images/time-fill.png");
  background-position: center center;
  background-size: contain;
  background-repeat: no-repeat;
}

.gpu-profit {
  font-size: 13px;
  color: hsla(0, 0%, 100%, 0.6);
}

.countdown-operation-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 9px;
  color: rgb(246, 234, 222);
  font-size: 16px;
  background: rgba(254, 242, 230, 0.1);
}

.countdown-block {
  color: rgb(246, 234, 222);
  font-size: 16px;
  display: flex;
  margin-right: 11px;
}

.timer-label {
  font-size: 14px;
  padding-left: 11px;
}

.timer {
  font-size: 16px;
  color: #f39800;
  font-weight: 500;
  margin-left: 5px;
}

.operation-btns {
  display: flex;
  align-items: center;
}

.view-btn {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 8px;
  position: relative;
  z-index: 1;
}

.view-btn:active {
  opacity: 0.8;
}

.view-btn img {
  width: 45px;
  height: 34px;
  display: inline-block;
  vertical-align: middle;
}

.operate-btn {
  width: 143px;
  height: 34px;
  align-items: center;
  justify-content: center;
  background: url("@/assets/images/d-bg2.png") no-repeat center center;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  color: #0c1f26;
  font-size: 16px;
  font-weight: 700;
  position: relative;
  overflow: hidden;
}

.operate-btn.loading {
  padding-left: 6px;
  display: flex;
}

.operate-btn.can-receive {
  background: url("@/assets/images/d-bg2.png") no-repeat center center;
  background-size: 100% 100%;
  display: flex;
  justify-content: center;
}

.operate-btn.expired {
  background: rgba(128, 128, 128, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  color: #f6eade;
}

.loading-circle {
  border-radius: 50%;
  border-style: solid;
  color: rgb(12, 31, 38);
  width: 16px;
  height: 16px;
  border-color: rgb(12, 31, 38) rgba(255, 255, 255, 0.4)
    rgba(255, 255, 255, 0.4);
  animation: spin 1s linear infinite;
  margin-right: 6px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.gpu-details {
  padding: 15px;
  background: rgba(32, 27, 24, 0.95);
}

.detail-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: rgba(246, 234, 222, 0.6);
  flex-shrink: 0;
  text-align: left;
}

.detail-value {
  color: #f6eade;
  text-align: right;
}

.van-list {
  width: 100%;
  min-height: 100px;
}
</style>
